<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;

class Index extends Controller
{

    /**
     * 后台登录页面
     * @return \think\response\View
     */
    public function index()
    {
        return view('admin@index/login');
    }

    /**
     * 后台登录处理
     * @return \think\response\View
     */
    public function doLogin()
    {
        //接收用户名和密码
        $username = input('post.username');
        $userpass = input('post.userpass');

        //验证
        $data = Db::name('user')->where('username', $username)->find();
        if (!$data) {
            $this->error('用户名不存在！');
            exit;
        }
        //验证密码
        if ($data['userpass'] != md5($userpass)) {
            $this->error('密码不正确');
            exit;
        }
        //把用户信息添加到session
        Session::set('admin_user', $data);
        // var_dump($_SESSION);

        // $uid = $data['id'];
        // $rid = Db::name('user_role')->field('rid')->where('uid', $uid)->select();
        // dump($rid);
        // $nid = Db::name('role_node')->field('nid')->where('rid', 'in', $rid)->buildSql();
        // dump($nid);die;
        // $list = Db::name('node')->field('mname,aname')->where('id', $nid)->select();

        $list = Db::field('mname, aname')
                ->name('user u')
                ->join('user_role ur' , 'u.id = ur.uid')
                ->join('role_node rn' , 'ur.rid = rn.rid')
                ->join('node n', 'rn.nid = n.id')
                ->where('u.id = '.$data['id'])
                ->select();

        //控制器名转换为大写
        foreach ($list as $key => $val) {
            $list[$key]['mname'] = ucfirst($val['mname']);
        }
        // dump($list);

        $nodelist = array();
        $nodelist['Index'] = array('index');
        //遍历重新拼装
        foreach($list as $v){
            $nodelist[$v['mname']][] = $v['aname'];
            //把修改和执行修改 添加和执行添加 拼装到一起
            if($v['aname']=="edit"){
                $nodelist[$v['mname']][]="save";
            }
            if($v['aname']=="add"){
                $nodelist[$v['mname']][]="doadd";
            }
        }
        // dump($nodelist);die;
        //将权限信息放置到session中
        Session::set('nodelist', $nodelist);

        //重组的信息
        // dump($_SESSION['think']);die;

        $this->redirect('admin/Main/index');
    }

    /**
     * 后台登出处理
     * @return \think\response\View
     */
    public function logout()
    {
    	Session::clear();
        $this->redirect('admin/index/index');
    }

}